package com.geo.auth.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.geo.auth.entity.Role;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 角色Mapper接口
 */
@Mapper
public interface RoleMapper extends BaseMapper<Role> {
    
    /**
     * 根据角色代码查询角色
     */
    @Select("SELECT * FROM roles WHERE role_code = #{roleCode} AND deleted = 0")
    Role findByRoleCode(@Param("roleCode") String roleCode);
    
    /**
     * 根据用户ID查询用户拥有的角色
     */
    @Select("SELECT r.* FROM roles r " +
            "INNER JOIN user_roles ur ON r.id = ur.role_id " +
            "WHERE ur.user_id = #{userId} AND r.deleted = 0 AND ur.deleted = 0")
    List<Role> findByUserId(@Param("userId") String userId);
    
    /**
     * 查询所有启用的角色
     */
    @Select("SELECT * FROM roles WHERE status = 'ACTIVE' AND deleted = 0 ORDER BY sort_order ASC")
    List<Role> findActiveRoles();
    
    /**
     * 根据角色级别查询角色
     */
    @Select("SELECT * FROM roles WHERE role_level = #{level} AND deleted = 0")
    List<Role> findByLevel(@Param("level") Integer level);
    
    /**
     * 检查角色代码是否存在
     */
    @Select("SELECT COUNT(*) FROM roles WHERE role_code = #{roleCode} AND deleted = 0")
    int countByRoleCode(@Param("roleCode") String roleCode);
    
    /**
     * 兼容性方法 - 查询默认角色
     */
    @Select("SELECT * FROM roles WHERE is_default = 1 AND deleted = 0 LIMIT 1")
    Role selectDefaultRole();
    
    /**
     * 兼容性方法 - 根据用户ID查询角色
     */
    default List<Role> selectRolesByUserId(String userId) {
        return findByUserId(userId);
    }
    
    /**
     * 兼容性方法 - 根据用户ID查询角色（用于AuthService）
     */
    default List<Role> selectByUserId(String userId) {
        return findByUserId(userId);
    }
    
    /**
     * 兼容性方法 - 根据用户ID查询权限
     */
    default List<String> selectPermissionsByUserId(String userId) {
        // 这里应该实现查询用户权限的逻辑
        return List.of();
    }
}